import { PlusOutlined } from '@ant-design/icons'
import {
  Row,
  Col,
  Flex,
  Typography,
  Button,
  Form,
  Input,
  Select,
  Table,
  Alert,
  Switch,
  Modal,
  Radio,
  message
} from 'antd'
import React, { useEffect, useState, useRef } from 'react'
import {
  categoryAdd,
  categoryDel,
  categoryEdit,
  categoryList
} from '../service/content'

function ContentCategory() {
  // 更新dom
  const [n, setN] = useState(0)
  // 保存修改的id
  const [id, setId] = useState('')
  // 获取Form表单控件示例
  const [myForm] = Form.useForm()
  // 模态框标题
  const [modalTitle, setModalTitle] = useState('新增分类')
  // 创建表单的引用
  const formRef = useRef()
  // 模态框
  const [isModalOpen, setIsModalOpen] = useState(false)
  // 保存表格中选中的项
  const [selectedRowKeys, setSelectedRowKeys] = useState([])
  // 表格中是否有选中
  const hasSelected = selectedRowKeys.length > 0
  // 保存内容列表
  const [list, setList] = useState([])
  // 总页码
  const [total, setTotal] = useState(0)
  const [condition, setCondition] = useState({})
  const [pageNo, setPageNo] = useState(1)
  const request = async () => {
    const res = await categoryList({
      ...condition,
      pageNo: pageNo
    })
    console.log(res)
    setList(res.data.objects)
    setTotal(res.data.total)
  }
  useEffect(() => {
    request()
  }, [n, pageNo])
  return (
    <>
      <Row className="info">
        <Col span={24}>
          <Flex justify={'space-between'}>
            <Typography.Title level={4}>信息管理</Typography.Title>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={() => setIsModalOpen(true)}
            >
              新增分类
            </Button>
          </Flex>
        </Col>
      </Row>
      <Row className="container">
        <Col span={24}>
          <Form
            layout="inline"
            onFinish={(v) => {
              setCondition(v)
              setN(n + 1)
            }}
          >
            <Form.Item label="分类名称：" name="categoryName">
              <Input />
            </Form.Item>
            <Form.Item label="启用状态：" name="categoryStatus">
              <Select
                style={{ width: 120 }}
                options={[
                  {
                    value: '0',
                    label: '全部'
                  },
                  {
                    value: '1',
                    label: '启用'
                  },
                  {
                    value: '0',
                    label: '停用'
                  }
                ]}
              />
            </Form.Item>

            <Form.Item>
              <Button type="default" htmlType="reset">
                重置
              </Button>
            </Form.Item>
            <Form.Item>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
            </Form.Item>
          </Form>
        </Col>
      </Row>
      <Row className="container">
        <Col span={24}>
          <Typography.Paragraph style={{ fontSize: 16 }}>
            分类列表
          </Typography.Paragraph>
          {hasSelected && (
            <Alert
              message={`已经选择 ${selectedRowKeys.length} 项`}
              type="info"
              showIcon
            />
          )}
        </Col>
        <Col span={24}>
          <Table
            pagination={{
              total,
              defaultCurrent: 1,
              onChange: async (pno) => {
                setPageNo(pno)
              }
            }}
            rowKey="id"
            rowSelection={{
              selectedRowKeys,
              onChange: (newSelectedRowKeys) => {
                console.log('selectedRowKeys changed: ', newSelectedRowKeys)
                setSelectedRowKeys(newSelectedRowKeys)
              }
            }}
            dataSource={list}
            columns={[
              {
                title: '编号',
                dataIndex: 'id',
                key: 'id'
              },
              {
                title: '名称',
                dataIndex: 'categoryName',
                key: 'categoryName'
              },
              {
                title: '排序',
                dataIndex: 'sort',
                key: 'sort'
              },
              {
                title: '创建时间',
                dataIndex: 'createTime',
                key: 'createTime'
              },
              {
                title: '更新时间',
                dataIndex: 'updateTime',
                key: 'updateTime'
              },
              {
                title: '启用状态',
                dataIndex: 'categoryStatus',
                key: 'categoryStatus',
                render: (_, record) => {
                  return (
                    <Switch
                      defaultChecked={!!record.categoryStatus}
                      onChange={async (value) => {
                        const res = await categoryEdit({
                          id: record.id,
                          categoryStatus: +value
                        })
                        message.success('状态修改成功')
                      }}
                    />
                  )
                }
              },
              {
                title: '操作',
                dataIndex: 'op',
                key: 'op',
                align: 'center',
                render: (_, record) => {
                  return (
                    <span className="op">
                      <a
                        onClick={() => {
                          setIsModalOpen(true)
                          setModalTitle('编辑分类')
                          myForm.setFieldsValue(record)
                          setId(record.id)
                        }}
                      >
                        编辑
                      </a>
                      <a
                        onClick={async () => {
                          const res = await categoryDel({ id: record.id })
                          console.log(res)
                          if (res.code === '0') {
                            message.success('分类删除成功！')
                            setN(n + 1)
                          }
                        }}
                      >
                        删除
                      </a>
                    </span>
                  )
                }
              }
            ]}
          />
        </Col>
      </Row>
      {/* 模态框 */}
      <Modal
        title={modalTitle}
        open={isModalOpen}
        onOk={() => formRef.current.submit()}
        onCancel={() => {
          setIsModalOpen(false)
          setId('')
        }}
        maskClosable={false}
        width={700}
        destroyOnClose
      >
        <Form
          onFinish={async (v) => {
            console.log('ID:', id)
            console.log(v)
            if (!id) {
              // 新增分类
              const res = await categoryAdd(v)
              if (res.code == 0) {
                message.success('分类添加成功')
                setIsModalOpen(false)
              } else {
                message.error('分类添加失败，请重新添加')
              }
            } else {
              // 修改分类
              const res = await categoryEdit({ ...v, id })
              console.log(res)
              setId('')
              setIsModalOpen(false)
            }
            setN(n + 1)
          }}
          layout="vertical"
          //给form其名称
          form={myForm}
          ref={formRef}
          // 当字段被删除时不保留字段值
          preserve={false}
        >
          <Form.Item
            label="分类名称"
            name="categoryName"
            rules={[
              {
                required: true,
                message: '分类名称不能为空'
              }
            ]}
          >
            <Input placeholder="请输入分类名称" />
          </Form.Item>
          <Form.Item
            label="排序"
            name="sort"
            rules={[
              {
                required: true,
                message: '排序不能为空'
              }
            ]}
          >
            <Input placeholder="请输入排序" />
          </Form.Item>
          <Form.Item label="状态" name="categoryStatus">
            <Radio.Group>
              <Radio value={1}>启用</Radio>
              <Radio value={0}>禁用</Radio>
            </Radio.Group>
          </Form.Item>
        </Form>
      </Modal>
    </>
  )
}

export default ContentCategory
